<script setup>
import Hammer from 'hammerjs'
import {Player,AssetManager } from '@galacean/effects';
import wx from "weixin-js-sdk";
import {nextTick, onMounted, ref, unref} from "vue";
import homePage from '@/assets/aVersion/homePage.json'
import oneToOne from '@/assets/aVersion/oneToOne.json' //一比一
import threeToFour from '@/assets/aVersion/threeToFour.json' //三比四
import fourToThree from '@/assets/aVersion/fourToThree.json' //四比三
import message from '@/assets/aVersion/message.json' //寄语
import campusDetails from '@/assets/aVersion/campusDetails.json' //校区详情

import bHomePage from '@/assets/bVersion/homePage.json'
import bOneToOne from '@/assets/bVersion/oneToOne.json' //一比一
import bThreeToFour from '@/assets/bVersion/threeToFour.json' //三比四
import bFourToThree from '@/assets/bVersion/fourToThree.json' //四比三
import bMessage from '@/assets/bVersion/message.json' //寄语
import bCampusDetails from '@/assets/bVersion/campusDetails.json' //校区详情

import cHomePage from '@/assets/cVersion/homePage.json'
import cOneToOne from '@/assets/cVersion/oneToOne.json' //一比一
import cThreeToFour from '@/assets/cVersion/threeToFour.json' //三比四
import cFourToThree from '@/assets/cVersion/fourToThree.json' //四比三
import cMessage from '@/assets/cVersion/message.json' //寄语
import cCampusDetails from '@/assets/cVersion/campusDetails.json' //校区详情

import server from '@/utils/axios/server.js'
import {useRoute} from "vue-router";
import getWxConfig from "@/utils/wx/wxConfig.js";
const route = useRoute();
let  useVersion = 'aVersion'
//第一组
let firstGroup = ref({
  m1:{
    homePage,
    oneToOne,
    threeToFour,
    fourToThree,
    message,
    campusDetails,
  },
  m2:{
    homePage:bHomePage,
    oneToOne:bOneToOne,
    threeToFour:bThreeToFour,
    fourToThree:bFourToThree,
    message:bMessage,
    campusDetails:bCampusDetails,
  },
  m3:{
    homePage:cHomePage,cHomePage,
    oneToOne:cOneToOne,
    threeToFour:cThreeToFour,
    fourToThree:cFourToThree,
    message:cMessage,
    campusDetails:cCampusDetails,
  },
})
let index = ref(0)
let con = ref(null)
let player = ref(null)
let baseInfoForm = ref({})
let cArray = ref({})
let collection = ref({})
let num = ref(0)
let isLoading = ref(false)
let compositionList = ref([]);
let lock = false
let portfolioImgJson = ref([])
let workType = ref('m1')
let url = null
// 2. 加载并播放动效资源
onMounted(() => {
  getWxConfig()
  getApiAcquireWorkPortfolio()
})

const customShare = async () => {
  let shareData = {
    title: `${baseInfoForm.value.studentName}的《${baseInfoForm.value.term}课程》佳作集锦`,  //分享的标题
    desc: '见证宝贝的每一次创作和成长,希望在未来的日子里，继续创作，做生活的艺术家~',  //分享的描述
    link: window.location.href,   //分享的链接
    imgUrl:'http://dwart-public.oss-cn-zhangjiakou.aliyuncs.com/cdn/imgs/shareLogo.png', //分享的图片链接
    success(response) {
      //配置成功之后的回调（并不是分享成功之后的回调，这个地方是个坑，要注意下）
    },
    fail(v){

    }
  };
  wx.ready(()=>{
    wx.updateAppMessageShareData(shareData)
    wx.updateTimelineShareData(shareData)
  })
}
const advanceLoading = () => {
  // assetManager.loadScene(oneToOne,  player.renderer,) .then(scene => player.loadScene(scene))
}

const getAllCompositions = async () => {
  compositionList.value = [
    {
      json: firstGroup.value[workType.value].homePage,
      studentName: baseInfoForm.value.studentName,
      age: baseInfoForm.value.age,
      term:baseInfoForm.value.term,
      teacher:baseInfoForm.value.teacher,
    },
  ]
  cArray.value.map(v=>{
    const { h,w,url } = v.imgs.find(v=>v.zIndex === 20)
    if ( v.type === '1' ) {
      compositionList.value.push({json:firstGroup.value[workType.value].oneToOne,url:url,data:v})
      //一比一
    }else if (  v.type === '2' ) {
      //三比四
      compositionList.value.push({json:firstGroup.value[workType.value].threeToFour,url:url,data:v})
    }else {
      //四比三
      compositionList.value.push({json:firstGroup.value[workType.value].fourToThree,url,data:v})
    }
  })
  compositionList.value.push({json:firstGroup.value[workType.value].message,j:collection.value.j})
  compositionList.value.push({json:firstGroup.value[workType.value].campusDetails,d:collection.value.d})
}

const play = (page = 0) => {
  initpPlayer(page)
  let uParagraph,j,url,data,d,qrCode,matchResult
  if ( compositionList.value[page].j ) {
    j = compositionList.value[page].j
    uParagraph = j.textBook[0].content
  }
  if (  compositionList.value[page].url ) {
    url = compositionList.value[page].url
  }
  if (   compositionList.value[page].data ) {
    data = compositionList.value[page].data
  }
  if ( compositionList.value[page].d ) {
    d = compositionList.value[page].d
    qrCode = d.imgs[d.imgs.length -1].url
    matchResult = d.textBook[1].content ? d.textBook[1].content.split('\n') : ['',''];
  }
  player.loadScene(compositionList.value[page].json,{
    variables: {
      dw11:url,
      dw34:url,
      dw43:url,
      dwqrCode:qrCode ? qrCode : 'http://dwart-test2.oss-cn-zhangjiakou.aliyuncs.com/dw_work_collections/m1/d/qrCode.png',// 如果图片加载失败，将会触发加载失败
    },
    templateScale: 1, // 缩放比例，如果图片比较糊，可以用2（但会增大图片内存）
  }).then(composition =>{
    modifyingText(composition, 'uName', `姓名：${baseInfoForm.value.studentName}`)
    modifyingText(composition, 'uAge', `年龄：${baseInfoForm.value.age ? baseInfoForm.value.age: ''}`)
    modifyingText(composition, 'uSemester', `学期：${baseInfoForm.value.term}`)
    modifyingText(composition, 'uTeacher', `老师：${baseInfoForm.value.teacher}`)
    if ( data  ) {
      modifyingText(composition, 'uTopic', `${data.text[0].content}`)
      modifyingText(composition, 'uKnowledge', `${data.textBook[0].content}`)
      modifyingText(composition, 'uTopic1', `${data.text[0].content}`)
      modifyingText(composition, 'uKnowledge1', `${data.textBook[0].content}`)
      modifyingText(composition, 'uTopic2', `${data.text[0].content}`)
      modifyingText(composition, 'uKnowledge2', `${data.textBook[0].content}`)
      modifyingText(composition, 'uTopic3', `${data.text[0].content}`)
      modifyingText(composition, 'uKnowledge3', `${data.textBook[0].content}`)
    }
    if ( d ) {
      modifyingText(composition, 'uAddress', `${matchResult[0]}`)
      modifyingText(composition, 'uTelephone', `${matchResult[1]}`)
      modifyingText(composition, 'uCampus', `${ d.textBook[0].content}`)
      modifyingText(composition, 'uAddress2', `${matchResult[0]}`)
      modifyingText(composition, 'uTelephone2', `${matchResult[1]}`)
      modifyingText(composition, 'uCampus2', `${ d.textBook[0].content}`)
    }
    if ( j ) {
      modifyingText(composition, 'uParagraph', `${j.textBook[0].content}`)
    }
    lock = false
  }).catch(v=>{

  })
}

const initHammer = () => {
  let mc, swipe;
  mc = new Hammer.Manager(unref(con));
  swipe = new Hammer.Swipe()
  mc.add(swipe)
  mc.on('swipeup', (v) => {
    //下一页
    if ( lock ) return;
    if ( index.value === compositionList.value.length - 1 ) return
    index.value++
    destroyPlayer()
    lock = true
    play(index.value)
  })
  mc.on('swipedown', (v) => {
    //上一页
    if ( lock ) return;
    if ( index.value <= 0 ) return
    index.value--
    destroyPlayer()
    lock = true
    play(index.value)
  })
}

const preloading = () => {
  let loadmanifest = []
  let queue = new createjs.LoadQueue(true);
  cArray.value.map(v => {
    const { url } = v.imgs.find(v=>v.zIndex === 20)
    loadmanifest.push(url)
  })
  for (const key in firstGroup.value[workType.value]) {
    firstGroup.value[workType.value][key].fonts.forEach(v => {
      loadmanifest.push (imagesUrlChange(v.fontURL.pathname ? v.fontURL.pathname : v.fontURL).pathname)
    })
    firstGroup.value[workType.value][key].images.forEach(v => {
      loadmanifest.push(imagesUrlChange(v.url.pathname ? v.url.pathname : v.url).pathname)
      loadmanifest.push(imagesUrlChange(v.webp.pathname?v.webp.pathname:v.webp).pathname)
    })
  }
  queue.loadManifest(loadmanifest);
  queue.on('progress', ()=>{
    num.value = `${Math.floor(queue.progress * 100)}%`;
  });
// 加载完成时，监听全部文件加载完成的那一刻，并回调 handleComplete 函数。
  queue.on('complete', (v)=>{
    isLoading.value = true;
    nextTick()
    initHammer()
    play()
  });
}
const initpPlayer = (page) => {
    player = new Player({
      container: document.getElementById('container'),
      pixelRatio: window.devicePixelRatio || 2,
      interactive: true,
      onItemClicked:(item)=>{
        if ( item.name === 'interact_28' ) {
          index.value = 1
          destroyPlayer()
          play(1)
        }
      }
    });
  advanceLoading()
  compositionList.value[page].json.images.forEach(v => {
    v.url = imagesUrlChange(v.url.pathname ? v.url.pathname : v.url)
    v.webp = imagesUrlChange(v.webp.pathname ? v.webp.pathname : v.webp)
  })
  compositionList.value[page].json.fonts.forEach(v => {
    v.fontURL = imagesUrlChange(v.fontURL.pathname ? v.fontURL.pathname : v.fontURL)
  })
}
const getApiAcquireWorkPortfolio = async () => {
  let res = await server.post('/dwart/theTeaching/workPortfolio/acquireWorkPortfolio', {
    id: route.query.id
  })
  let detailsJson = JSON.parse(res.data.data.detailsJson)
  workType.value = detailsJson.workType
  portfolioImgJson.value = JSON.parse(res.data.data.portfolioImgJson)
  cArray.value = Object.keys(detailsJson.collection)
      .filter(key => key.startsWith('c'))
      .map(key => detailsJson.collection[key]);
  baseInfoForm.value = detailsJson.baseInfoForm
  collection.value = detailsJson.collection
  await getAllCompositions();
  getUseVersion( workType.value)
  preloading()
  document.title = `${baseInfoForm.value.studentName}的${baseInfoForm.value.year}年${baseInfoForm.value.term}课程`
  await customShare()
}
const getUseVersion = (m) => {
  let prefix = import.meta.env.MODE === "production"  ?
      'https://img.dwhs.cn/cdn/dw_work_collections/' :
      'https://dwart-test2.oss-cn-zhangjiakou.aliyuncs.com/dw_work_collections/'
  switch (m) {
    case 'm1':
      useVersion = 'aVersion'
      url = prefix + 'm1/bg.png'
      return
    case 'm2':
      useVersion = 'bVersion'
      url = prefix + 'm2/d/bg.png'
      return;
    case  'm3':
      useVersion = 'cVersion'
      url = prefix + 'm3/bg.png'
      return;
  }

}
const imagesUrlChange = (url) => {
  return new URL(url.replace('.\/', `../assets/${useVersion}/`), import.meta.url)
}
const modifyingText = (composition, itemByName, setText) => {
    const item = composition.getItemByName(itemByName)
    if ( item ) {
      item.textContext.options.text = `${setText}`
      item.content?.setText(`${setText}`)
    }
}

//销毁一个播放器
const destroyPlayer = () => {
  player?.dispose()
}
</script>

<template>
  <div v-if="!isLoading" style="width: 100vw;height: 100vh">
    <article class="article-box article-one" :style="{backgroundImage: `url('${url}')`, backgroundSize: '100% 100%'}"  >
      <div class="progress">
        <span>{{num}}</span>
        <div class="progress-status"></div>
      </div>
    </article>
  </div>
  <div style="overflow: hidden;"
       :style="{backgroundImage: `url('${url}')`, backgroundSize: '100% 100%',backgroundColor:'#f4c71c'}" ref="con" class="con">
    <div id="container" style="width: 100vw;height: 100vh"></div>
  </div>
</template>

<style scoped>
.con {
  background-size: 100% 100%;
  width: 100vw;
  height: 100vh;
}
.article-box {
  display: none;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  position: absolute;
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
}
.article-box .progress {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  position: relative;
  width: 70vw;
  height: 8vw;
  background: transparent;
  border: 3px solid #fff;
  border-radius: 10vw;
  -webkit-box-shadow: 2px 3px 4px 0px #505050;
  box-shadow: 2px 3px 4px 0px #505050;
  overflow: hidden;
  background-color: #B2F70C;
}
.article-box .progress span {
  position: absolute;
  left: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  z-index: 20;
  -webkit-animation: progressAnimate 1s linear 0s infinite alternate;
  animation: progressAnimate 1s linear 0s infinite alternate;
  color: #0F0F0F;
  font-weight: bold;
}
@-webkit-keyframes progressAnimate {
  from {
    opacity: 0.2;
  }
  to {
    opacity: 1;
  }
}

@keyframes progressAnimate {
  from {
    opacity: 0.2;
  }
  to {
    opacity: 1;
  }
}
.article-box .progress .progress-status {
  position: absolute;
  -webkit-transition: 0.1s;
  transition: 0.1s;
  left: 0;
  width: 0%;
  height: 100%;
  background: #f39c12;
}
.article-one {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  //background: #1abc9c;
}
.article-two {
  //background: #16a085;
}
</style>
